package com.whvronk.server;

import com.whvronk.server.codec.DataFrameDecoder;
import com.whvronk.server.codec.DataFrameEncoder;
import com.whvronk.server.codec.DataProtocolDecoder;
import com.whvronk.server.codec.DataProtocolEncoder;
import com.whvronk.server.handler.DataServerProcessHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;

@Slf4j
public class SeverApp {

    private static ApplicationContext applicationContext;

    public SeverApp(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    public static void main(String[] args) {
        try {
            ServerBootstrap bootstrap = new ServerBootstrap(); //ServerBootstrap是Netty的核心入口,主要是配置服务器和启动的过程.
            bootstrap.channel(NioServerSocketChannel.class); //选择使用NIO来进行网络通信
            bootstrap.group(new NioEventLoopGroup()); //设置处理IO的操作
            bootstrap.handler(new LoggingHandler(LogLevel.INFO));
            bootstrap.childHandler(new ChannelInitializer<NioSocketChannel>() {
                @Override
                protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                    ChannelPipeline pipeline = nioSocketChannel.pipeline();
                    pipeline.addLast(new DataFrameDecoder());
                    pipeline.addLast(new DataFrameEncoder());
                    pipeline.addLast(new DataProtocolDecoder());
                    pipeline.addLast(new DataProtocolEncoder());

                    pipeline.addLast(new LoggingHandler(LogLevel.INFO));
                    pipeline.addLast(new DataServerProcessHandler(applicationContext));
                }
            });
            ChannelFuture channelFuture = bootstrap.bind(9999).sync();
            channelFuture.channel().closeFuture().get();

        } catch (Exception e) {
            log.error("exception:{}", e.getMessage());
        }

    }

}
